//
//  WBNetworkManager+extension.swift
//  DJWeibo
//
//  Created by demo on 2017/4/4.
//  Copyright © 2017年 demo. All rights reserved.
//

import Foundation

//Mark: -封装新浪微博的网络请求方法
extension WBNetworkManager{

    //加载微博数据字典数组
    //-parameters completion:完成回调[list:微博字典数组／是否成功]
    func statusList(since_id:Int64 = 0,max_id:Int64 = 0, completion:@escaping (_ list:[[String:Any]]?, _ isSuccess: Bool)->()){
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json?"
        
        let params = ["since_id":since_id,"max_id":max_id > 0 ? max_id - 1 : 0]
        
       // let params = ["access_token":"2.00HlY2nBMaeLpDf54fc7c07e0m9bfX"]
        
        //网络工具单例，用静态变量存储返回的值
        //        WBNetworkManager.shared.get(urlString, parameters: params, progress: nil, success: { (_, json) in
        //            print(json)
        //        }) { (_, error) in
        //            print("网络请求失败\(error)")
        //        }
        tokenRequest(URLString: urlString, parameters: params) {
            //返回数据回调方法，返回的是json和isSuccess
            (json, isSuccess) in
            //print(json)
            //此处json要先转成NSDictionary,否则会报错
            //从json中获取statuses字典数组／如果第二个as?失败，result=nil
            
            //服务器返回的json是按照时间的倒序排序的
            let result = (json as? NSDictionary)?["statuses"] as? [[String:Any]]
            
            completion(result,isSuccess)
        }
    }
    //返回未读微博数
    func unreadCount(completion:@escaping (_ count:Int)->()){
        guard let uid = uid else {
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid":uid]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            print(json)
            
            let dict = json as? [String:Any]
            let count = dict?["status"] as? Int
            completion(count ?? 0)
        }
        
    }
}
